﻿Function Add-AzureSearchDocument($indexName,[hashtable]$properties)
{
    Import-Module -Force ..\Utilities\libJSON.psm1

    $baseUrl="https://<search service name>.search.windows.net"
    $addDocumentUrl="/indexes/$indexName/docs/index?api-version=2014-07-31-Preview"

    $actionFullUrl=$baseUrl+$addDocumentUrl

    $body = '{
      "value": [
        {
          "@search.action": "mergeOrUpload",'

    $propertyCount=$properties.Count
    $currentPropertyIndex=1
    foreach($property in $properties.GetEnumerator())
    {
        $body+='"' + $property.Key + '":"' + (Get-EscapedJSONBody -originalBody $property.Value) + '"'
        if($currentPropertyIndex -ne  $propertyCount)
        {
            $body+=","    
        }

        $currentPropertyIndex++
    }


    $body+='}
      ]
    }'
    #$body=Get-EscapedJSONBody -originalBody $body
    try
    {
        Invoke-RestMethod -Method Post -Uri $actionFullUrl -Body $body -Headers @{"api-key"="<apikey>";"charset"="utf-8"} -ContentType "application/json"
    }
    catch
    {
        $_
    }

}

Function Remove-AzureSearchDocument($indexName,$keyFieldName,$key)
{
    $baseUrl="https://<search service name>.search.windows.net"
    $addDocumentUrl="/indexes/$indexName/docs/index?api-version=2014-07-31-Preview"
    
    $body = '{
      "value": [
        {
          "@search.action": "delete","'+ $keyFieldName +'":"' + $key + '"'
    +'}
      ]
    }'

    try
    {
        Invoke-RestMethod -Method Post -Uri $actionFullUrl -Body $body -Headers @{"api-key"="<apikey>";"charset"="utf-8"} -ContentType "application/json"
    }
    catch
    {
        $_
    }    
}

Function Remove-AzureSearchIndex($indexName)
{
    $baseUrl="https://<search service name>.search.windows.net"
    $indexUrl="/indexes/$indexName`?api-version=2014-07-31-Preview&"

    $actionFullUrl=$baseUrl+$indexUrl

    Invoke-RestMethod -Method DELETE -Uri $actionFullUrl -Headers @{"api-key"="<apikey>"} -ContentType "application/json"
}



Function Get-AzureSearchIndex($indexName)
{
    $baseUrl="https://<search service name>.search.windows.net"
    if($indexName -ne $null)
    {
        $indexUrl="/indexes/$indexName`?api-version=2014-07-31-Preview&"
    }
    else
    {
        $indexUrl="/indexes`?api-version=2014-07-31-Preview&"
    }

    $actionFullUrl=$baseUrl+$indexUrl

    Invoke-RestMethod -Method GET -Uri $actionFullUrl -Headers @{"api-key"="<apikey>"} -ContentType "application/json"
}

Function Query-AzureSearchDocument($indexName,$searchQuery)
{
    $baseUrl="https://<search service name>.search.windows.net"
    $searchDocumentUrl="/indexes/$indexName/docs?api-version=2014-07-31-Preview&"

    $actionFullUrl=$baseUrl+$searchDocumentUrl+$searchQuery

    Invoke-RestMethod -Method GET -Uri $actionFullUrl -Headers @{"api-key"="<apikey>"} -ContentType "application/json"
}